package com.ruoyi.system.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class FileService {
    private static String base;

    @Value("${file.base:files}")
    public void setBase(String dir) {
        if (!dir.endsWith("/")) {
            dir += "/";
        }
        FileService.base = dir;
    }

    private static void createDir(String fullpath) {
        File file = new File(fullpath);
        if  (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static String getFullPath(String path) {
        return FileService.base + path;
    }

    public static Boolean save(String path, String content, Boolean decode) {
        Boolean done = false;
        String dir = path.substring(0, path.lastIndexOf("/"));
        String name = path.substring(path.lastIndexOf("/") + 1);
        FileService.createDir(FileService.base + dir);
        try {
            File file = new File(FileService.base + dir, name);
            byte[] bytes = content.getBytes();
            byte[] raw = null;
            if (decode) {
                raw = Base64.getDecoder().decode(bytes);
            } else {
                raw = bytes;
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(raw);
            bos.close();
            done = true;
        } catch (IOException e) {
            log.info("",e);
        }
        return done;
    }

    public static String load(String path, Boolean encode) {
        String content = null;
        String fullpath = FileService.base + path;
        File file = new File(fullpath);
        log.info("load file: " + file.getAbsolutePath());
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            byte[] raw = bis.readAllBytes();
            if (encode) {
                content = Base64.getEncoder().encodeToString(raw);
            } else {
                content = new String(raw, "utf-8");
            }
            bis.close();
        } catch (IOException e) {
            log.info("",e);
        }
        return content;
    }

    public static Boolean find(String path) {
        String fullpath = FileService.base + path;
        File file = new File(fullpath);
        return file.exists();
    }

    public static Boolean remove(String path) {
        String fullpath = FileService.base + path;
        return new File(fullpath).delete();
    }

    public static void buildFileStream(String filename, String raw, HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "utf-8"));
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(raw.getBytes());
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
